﻿using System.IO;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace Machinery.Cogs
{
    public interface IDatabaseCreatorCog
    {
        /// <summary>
        /// Creates tables in the database, generated from the classes in the Persistent assembly.
        /// </summary>
        void CreateTables();

        /// <summary>
        /// Drops all tables in the database, if they exist. Handy when unit testing.
        /// </summary>
        void DropTables();
    }

    public class DatabaseCreatorCog : Cog, IDatabaseCreatorCog
    {
        /// <summary>
        /// Creates tables in the database, generated from the classes in the Persistent assembly.
        /// </summary>
        public void CreateTables()
        {
            SchemaExport(false);
        }

        /// <summary>
        /// Drops all tables in the database, if they exist. Handy when unit testing.
        /// </summary>
        public void DropTables()
        {
            SchemaExport(true);
        }

        protected void SchemaExport(bool drop)
        {
            const bool action = false;
            const bool export = true;
            const TextWriter writer = null;
            new SchemaExport(Get<NHibernate.Cfg.Configuration>()).Execute(action, export, drop, Get<ISession>().Connection, writer);
        }

    }
}